package top.kaoshanji.q2ch16a;

import org.junit.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import top.kaoshanji.q2ch16a.model.Spittle;

import java.util.HashMap;
import java.util.Map;

/**
 * 演示一下RestTemplate功能
 * @author kaoshanji
 * ^_^
 * create time 2025/4/26 15:32
 */
public class SpittleApiController1Test {

    // 控制器的本地访问路径
    private final String ROOT_URI_CONTROLLER1 = "http://localhost:8890/q2-ch16a-spitter-api/spittles1/";

    /**
     * 代码清单test-q2ch16a-01：演示RestTemplate的getForObject方法
     */
    @Test
    public void testSpittleDetail() {

        RestTemplate template = new RestTemplate();
        Spittle spittle = template.getForObject(ROOT_URI_CONTROLLER1 + "spittleDetail/{spittleId}", Spittle.class, 11);

        System.out.println("演示RestTemplate的getForObject方法：" + spittle);
    }

    /**
     * 代码清单test-q2ch16a-02：演示RestTemplate的postForObject方法
     */
    @Test
    public void testSaveSpittle() {
        RestTemplate template = new RestTemplate();

        Spittle spittle = new Spittle();
        spittle.setId(111L);
        spittle.setMessage("消息");

        Map<String, String> map = template.postForObject(ROOT_URI_CONTROLLER1 + "saveSpittle", spittle, HashMap.class);

        System.out.println("演示RestTemplate的postForObject方法：" + map);

    }

    /**
     * 代码清单test-q2ch16a-02：演示RestTemplate的exchange方法
     */
    @Test
    public void testSaveSpittleEntity() {
        RestTemplate template = new RestTemplate();

        Spittle newSpittle = new Spittle();
        newSpittle.setId(111L);
        newSpittle.setMessage("消息");

        MultiValueMap<String, String> headerMap = new LinkedMultiValueMap<>();
        headerMap.add("Content-Type", "application/json");

        // 把表单对象和请求头一起传递进来
        HttpEntity<Object> requestEntity = new HttpEntity<>(newSpittle, headerMap);

        ResponseEntity<Spittle> response = template.exchange(ROOT_URI_CONTROLLER1 + "saveSpittleEntity",
                HttpMethod.POST, requestEntity, Spittle.class);

        Spittle spittle = response.getBody();

        System.out.println("演示RestTemplate的exchange方法：" + spittle);
    }


}
